package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.FreezeInfoApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.domain.FreezeInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FreezeInfoApi freezeInfoApi;

    @Autowired
    private OssTemplate template;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;


    //根据手机号查询用户ID
    public User findByMobile(String mobile) {
        return userApi.findByMobile(mobile);
    }

    //根据手机号和验证码判断用户信息
    public Map loginVerification(String mobile, String code) {
        //1、获取redis中的验证码
        String redisCode = redisTemplate.opsForValue().get("CODE:" + mobile);
        //2、比较用户输入的验证码和redis验证码是否一致
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //2.1 不一致，抛出异常
            throw new BusinessException(ErrorResult.loginError());
        }
        //2.2 一致，删除redis中的验证码数据
        redisTemplate.delete("CODE:" + mobile);
        //3、根据手机号码查询用户
        User user = userApi.findByMobile(mobile);
        String type = "0101";   //登录
        //4 如果用户不存在（新用户），注册用户（保存到用户表）
        Boolean isNew = false;
        if (user == null) {
            isNew = true;
            user = new User();
            user.setPassword("123456");
            user.setMobile(mobile);
            Long userId = userApi.save(user);
            user.setId(userId);
            //4.1 将用户信息注册到环信
            huanXinTemplate.createUser("hx" + user.getId(), "123456");
            //4.2 更新用户的环信账户和密码
            user.setHxUser("hx" + user.getId());
            user.setHxPassword("123456");
            userApi.update(user);
            type = "0102";  //注册
        }
        mqMessageService.sendLogMessage(user.getId(), type, "log.user", null);
        //5、生成jwt的token字符串
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", user.getMobile());
        String token = JwtUtils.getToken(tokenMap);
        //6、构建返回
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;

    }

    //保存用户信息
    public void saveUserInfo(UserInfo userInfo) {
        userInfoApi.saveUserInfo(userInfo);
    }

    //上传用户图像
    public void head(Long id, MultipartFile headPhoto) throws IOException {
        //1. 上传到阿里云oss
        String url = template.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());

        //2. 判断头像中是否包含人脸
        Boolean detect = aipFaceTemplate.detect(url);
        if (!detect) {
            // TODO by 不包含人脸,在阿里云中进行删除-------------------------------作业
            template.deleteImage(url);
            throw new BusinessException(ErrorResult.faceError());
        }

        //3. 调用api，更新userinfo
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);
        userInfoApi.update(userInfo);

    }

    //冻结--根据用户id判断用户状态
    public void judgeUserStatus(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        if (userInfo.getUserStatus().equals("2")) {
            //根据userId查询冻结信息
            FreezeInfo freezeInfo = freezeInfoApi.findByUserId(id);
            //获取冻结时间和被冻结的日期
            Integer freezingTime = freezeInfo.getFreezingTime();
            Date freezeDate = freezeInfo.getCreated();
            if (freezingTime == 1) {
                //冻结时间为3天
                Date today = new Date();//当前时间
                if (today.getTime() >= freezeDate.getTime() + 1000 * 60 * 60 * 24 * 3) {
                    //1. 若时间过去了3天，就将冻结数据删除
                    freezeInfoApi.deleteByUserId(Integer.valueOf(id + ""));
                    //2. 将用户信息表中的用户状态修改过来,并保存
                    userInfo.setUserStatus("1");
                    userInfoApi.update(userInfo);
                    throw new BusinessException(new ErrorResult("9999", "该用户冻结状态已被清除"));
                }
            } else if (freezingTime == 2) {
                //冻结时间为7天
                Date today = new Date();//当前时间
                if (today.getTime() >= freezeDate.getTime() + 1000 * 60 * 60 * 24 * 7) {
                    //若时间过去了7天，就将冻结数据删除
                    freezeInfoApi.deleteByUserId(Integer.valueOf(id + ""));
                    //2. 将用户信息表中的用户状态修改过来,并保存
                    userInfo.setUserStatus("1");
                    userInfoApi.update(userInfo);
                    throw new BusinessException(new ErrorResult("9999", "该用户冻结状态已被清除"));
                }
            }
            if (freezeInfo.getFreezingRange() == 1) {
                throw new BusinessException(ErrorResult.freeze());
            }
        }
    }
}
